/*
 * Copyright (c) 2013 - 2015, Freescale Semiconductor, Inc.
 * Copyright 2016-2017 NXP
 * All rights reserved.
 *
 * SPDX-License-Identifier: BSD-3-Clause
 */

#include "board.h"
#include "clock_config.h"
#include "fsl_debug_console.h"
#include "fsl_device_registers.h"
#include "pin_mux.h"

// JLinkGDBServer -select USB -device MIMXRT1061xxx5A -endian little -if SWD
// -speed 4000 -noir -LocalhostOnly
/*******************************************************************************
 * Definitions
 ******************************************************************************/

/*******************************************************************************
 * Prototypes
 ******************************************************************************/

/*******************************************************************************
 * Code
 ******************************************************************************/
/*!
 * @brief Main function
 */

void setup_gpio_test(void) {}

void gpio_test_main(void) {
  while (1) {
    static int led_level;
    led_level = GPIO_PinRead(BOARD_INITPINS_KEY2_GPIO,BOARD_INITPINS_KEY2_GPIO_PIN);
    GPIO_PinWrite(BOARD_INITPINS_LED3_GPIO, BOARD_INITPINS_LED3_GPIO_PIN,
                  led_level);
    GPIO_PinWrite(BOARD_INITPINS_LED4_GPIO, BOARD_INITPINS_LED4_GPIO_PIN,
                  !led_level);
    SDK_DelayAtLeastUs(100000, CLOCK_GetCoreSysClkFreq());
  }
}

static int irq_flag = 0;
void irq_test_main(void) {
  while (1) {
    while(irq_flag == 0);
    static int led_level = 0;
    GPIO_PinWrite(BOARD_INITPINS_LED3_GPIO, BOARD_INITPINS_LED3_GPIO_PIN,
                  led_level);
    GPIO_PinWrite(BOARD_INITPINS_LED4_GPIO, BOARD_INITPINS_LED4_GPIO_PIN,
                  !led_level);
                  led_level = !led_level;
    SDK_DelayAtLeastUs(100000, CLOCK_GetCoreSysClkFreq());
    irq_flag = 0;
  }
}
void GPIO5_Combined_0_15_IRQHandler(){
     GPIO_PortClearInterruptFlags(BOARD_INITPINS_KEY2_GPIO,BOARD_INITPINS_KEY2_GPIO_PIN_MASK );
    irq_flag = 1;
    SDK_ISR_EXIT_BARRIER;
}

void setup_irq_test(){
    EnableIRQ(BOARD_KEY2_GPIO_IRQ);
    GPIO_PortEnableInterrupts(BOARD_INITPINS_KEY2_GPIO,BOARD_INITPINS_KEY2_GPIO_PIN_MASK );
}

int main(void) {
  /* Init board hardware. */
  BOARD_ConfigMPU();
  BOARD_InitBootPins();
  BOARD_InitBootClocks();
  BOARD_InitDebugConsole();

  PRINTF("demo.\r\n");

  setup_irq_test();
  irq_test_main();
  while (1) {
  };
}
